package com.jwpdk.dbframework;

import java.util.Stack;
/**
 * 事务管理器
 * @author 王志伟
 */
public class TransactionManager {

	private static Stack<Transaction> transactionStack = new Stack<Transaction>();

	private static TransactionManager transactionManager = null;

	private TransactionManager() {
	}

	public static TransactionManager getInstance() {
		if (transactionManager == null) {
			transactionManager = new TransactionManager();
		}
		return transactionManager;
	}
	
	/**
	 * 获取当前使用的事务
	 * @return
	 */
	public Transaction getCurrenTransaction() {
		return transactionStack.peek();
	}
	
	/**
	 * 事务是否存在
	 * @param Transaction
	 * @return
	 */
	public boolean containsTransaction(Transaction transaction) {
		return transactionStack.contains(transaction);
	}
	
	/**
	 * 获取事务对象 
	 * @param transactionName
	 * @return
	 */
	public Transaction geTransaction(String transactionName) {
		Transaction rsTransaction = null;
		for (Transaction transaction : transactionStack) {
			if(transaction.getTransactionName().equals(transactionName)){
				rsTransaction = transaction;
				break;
			}
		}
		return rsTransaction;
	}
	
	/**
	 * 开启事务，并将其他使用的事务当前属性设置为fasle
	 * @param transaction
	 * @throws Exception
	 */
	public void beginTransaction(Transaction transaction) throws Exception {
		if (containsTransaction(transaction) ) {
			throw new Exception(transaction.getTransactionName() + " 事务已存在！");
		}
		transactionStack.push(transaction);
		transaction.beginTransaction();
	}

	/** 提交事务并关闭连接 */
	public void endTransaction(Transaction transaction) throws Exception {
		if ( !containsTransaction(transaction) ) {
			throw new Exception(transaction.getTransactionName() + " 事务不存在或未加入管理器！！");
		}
		remove(transaction);
		transaction.endTransaction();
	}

	/** 回滚并关闭连接 */
	public void rollbackTransaction(Transaction transaction) throws Exception {
		if ( !containsTransaction(transaction) ) {
			throw new Exception(transaction.getTransactionName() + " 事务不存在或未加入管理器！！");
		}
		remove(transaction);
		transaction.rollbackTransaction();
	}
	/**
	 * 从栈中移除对象
	 * @param transaction
	 */
	private void remove(Transaction transaction){
		while (containsTransaction(transaction)) {
			transactionStack.remove(transaction);
		}
	}
}
